#!/usr/bin/perl

use strict 'vars';
package main;

use Getopt::Std;

use vars qw($opt_f $opt_u);
#get command line options
getopts('f:');
    
die "In the process of debugging\n";
if ($opt_f eq "") {
    die "Usage:  format_usage -f <file name> -u <slice name>\n";
}
if ($opt_u eq "") {
    $opt_u = "ucb6";
}

my %hosts = (); my %usernames = (); my %usage = ();
open INFILE, $opt_f;
my $new_host = 1; my $line; my @fields; my $last_host;
while ($line = <INFILE>) {
    chomp $line;
    
    if ($new_host) {
	$last_host = $line;
	$hosts{$line} = 1;
	$new_host = 0;
	next;
    }

    if ($line eq "") {
	$new_host = 1;
	next;
    }

    @fields = split " ", $line;
    $usernames{$fields[1]}++;
    $usage{"$fields[1] $last_host"} = $fields[0];
}

#html head
print "<html>\n<head><title>ucb6 usage</title>\n</head>\n";
print "<body  bgcolor=\"#ffffff\" text=\"#000000\" link=\"#0000cc\" vlink=\"#cc00cc\" alink=\"#cc0000\"><center>\n";
print "<h1>Disk usage of ucb6 slice</h1>\n";

print "<div ALIGN=CENTER>\n<table ALIGN=CENTER BORDER=1>\n<tr ALIGN=CENTER>\n";
print "<td width=80 BGCOLOR=white>&nbsp;<br>Non-existent</td>\n";
print "<td width=80 BGCOLOR=\"#FFFBF0\">&nbsp;<br>< 999KB</td>\n";
print "<td width=80 BGCOLOR=yellow>&nbsp;<br>< 50MB</td>\n";
print "<td width=80 BGCOLOR=orange>&nbsp;<br>< 500MB</td>\n";
print "<td width=80 BGCOLOR=red>&nbsp;<br>> 500MB</td>\n";
print "</tr></table></div><p>";

#init table
print "<p>\n<center><table BORDER>\n";

print "<tr BGCOLOR=\"#FFFFFF\" NOSAVE>\n<td><font FACE=\"Times New Roman,Times\">";
print "<b>Host name</b>";

my $host; my $username;
foreach $username (sort by_value keys %usernames) {
    print "</font></td>\n<td><font FACE=\"Times New Roman,Times\">";
    print "$username";
}
print "</font></td>\n</tr>\n";

foreach $host (sort keys %hosts) {
    print "</font></td>\n<td><font FACE=\"Times New Roman,Times\">";
    print "$host";
    foreach $username (sort by_value keys %usernames) {
	my $bgcolor = "silver";
	my $use = 0; my $num;
	if (!exists($usage{"$username $host"})) {
	    $bgcolor = "white";
	    $use = "-";
	} else {
	    $use = $usage{"$username $host"};
	    if ($use =~ /G/) {
		$bgcolor = "red";
	    } elsif ($use =~ /M/) {
		$num = $use;
		chop($num);
		if ($num < 50) {
		    $bgcolor = "yellow";
		} elsif ($num < 500) {
		    $bgcolor = "orange";
		} else {
		    $bgcolor = "red";
		}
	    } else {
		$bgcolor = "#FFFBF0";
	    }
	}
	
	print "</font></td>\n<td BGCOLOR=$bgcolor><font FACE=\"Times New Roman,Times\">";
	print $use;
    }
    print "</font></td>\n</tr>\n";
}

print "</table></center>\n";

sub by_value { $usernames{$b} <=> $usernames{$a}; }
